package com.zy.ch1.controller;

import com.zy.ch1.entity.Book;
import com.zy.ch1.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    BookService bookService;

    @PostMapping("findBooks")
    public ResponseEntity findBooks(){
      List<Book> books =  bookService.findBooks();
      return new ResponseEntity(books, HttpStatus.OK);
    }

    @PostMapping("selectBooks")
    public ResponseEntity selectBooks(
            @RequestParam String bookName,@RequestParam String bookType,@RequestParam String bookAuthor,
            @RequestParam int pageNum,@RequestParam int pageSize){
        Map<String,Object> map = new HashMap<String ,Object>();
        if(StringUtils.isNotBlank(bookName)){
            map.put("bookName",bookName);
        }
        if(StringUtils.isNotBlank(bookType)){
            map.put("bookType",bookType);
        }
        if(StringUtils.isNotBlank(bookAuthor)){
            map.put("bookAuthor",bookAuthor);
        }
        List<Book> books =  bookService.selectBooks(map,pageNum,pageSize);
        return new ResponseEntity(books, HttpStatus.OK);
    }

    @DeleteMapping("deleteBook")
    public ResponseEntity deleteBook(@RequestParam String bookName){
       int count =  bookService.deleteBookByBookName(bookName);
       return new ResponseEntity(count, HttpStatus.OK);
    }

    @PostMapping("updateBook")
    public ResponseEntity updateBook(
            @RequestParam String bookName,@RequestParam String bookType,
            @RequestParam String bookAuthor,@RequestParam Integer id){
        Map<String,Object> map = new HashMap<String ,Object>();
        map.put("id",id);
        if(StringUtils.isNotBlank(bookName)){
            map.put("bookName",bookName);
        }
        if(StringUtils.isNotBlank(bookType)){
            map.put("bookType",bookType);
        }
        if(StringUtils.isNotBlank(bookAuthor)){
            map.put("bookAuthor",bookAuthor);
        }
        int count = bookService.updateBook(map);
        return new ResponseEntity(count, HttpStatus.OK);
    }

    @PostMapping("insertBook")
    public ResponseEntity insertBook(
            @RequestParam String bookName,@RequestParam String bookType,@RequestParam String bookAuthor){
        Book book = new Book();
        book.setBookAuthor(bookAuthor);
        book.setBookName(bookName);
        book.setBookType(bookType);
        int count = bookService.insertBook(book);
        return new ResponseEntity(count, HttpStatus.OK);
    }

}
